package com.starbaba.stat.service.impl;

import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.google.common.collect.Lists;
import com.starbaba.base.dao.LoanManagerBaseDao;
import com.starbaba.core.service.CommonConditionService;
import com.starbaba.core.service.impl.CommonConditionServiceImpl;
import com.starbaba.stat.model.StatCommActivityRegisterModel;
import com.starbaba.stat.service.StatCommActivityRegisterService;
import org.apache.commons.lang3.StringUtils;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StatCommActivityRegisterServiceImpl extends LoanManagerBaseDao implements StatCommActivityRegisterService{


	private CommonConditionService commonConditionService = new CommonConditionServiceImpl();
	private Map<String, String> productGroupMap = new HashMap<>();
	private Map<String, String> channelGroupMap = new HashMap<>();
	private Map<String, String> secondaryChannelGroupMap = new HashMap<>();

	public StatCommActivityRegisterServiceImpl(){
		productGroupMap = commonConditionService.getParentProductMap();
		channelGroupMap = commonConditionService.getChannelGroupMap();
		secondaryChannelGroupMap = commonConditionService.getSecondaryChannelGroupMap();
	}

	@Override
	public List<StatCommActivityRegisterModel> getList(
			Map<String, Object> paramsMap, int pageNo, int pageSize) {
		
		String sql = generateGetListSql(paramsMap) + " ORDER BY cdate DESC LIMIT ?,? ";
		List<StatCommActivityRegisterModel> list = Lists.newArrayList();
		
		try {
			list = getStatDao().list(sql, StatCommActivityRegisterModel.class, pageNo, pageSize);
			if(list != null && list.size() > 0){
				
				for(StatCommActivityRegisterModel model: list){

					model.setProductGroupName(this.productGroupMap.get(model.getProductGroupId()));
					model.setChannelGroupName(this.channelGroupMap.get(model.getChannelGroupId()));
					model.setSecondaryChannelGroupName(this.secondaryChannelGroupMap.get(model.getSecondaryChannelGroupId()));

					DecimalFormat format = new DecimalFormat("#.##%");
					if(model.getLoginCount() == null || model.getUv() == null || model.getUv() == 0){
						model.setLoginToUvRate("0.00%");
					}else{
						model.setLoginToUvRate(format.format((double)model.getLoginCount() / (double)model.getUv()));
					}

					if(model.getAppRegisterCountPhone() == null || model.getUv() == null || model.getUv() == 0){
						model.setAppRegisterCountPhoneToUvRate("0.00%");
					}else{
						model.setAppRegisterCountPhoneToUvRate(format.format((double)model.getAppRegisterCountPhone() / (double) model.getUv()));
					}
				}
			}
			
		} catch (AppException e) {
			LogService.error(e);
		}
		
		return list;
	}
	
	@Override
	public int countList(Map<String, Object> paramsMap) {
		
		String sql = "SELECT COUNT(1) FROM ( " + generateGetListSql(paramsMap) + ") AS a" ;
		int result = 0;
		try {
			result = getStatDao().getInt(sql);
		} catch (AppException e) {
			LogService.error(e);
		}
		
		return result;
	}

	@Override
	public String exportList(Map<String, Object> paramsMap) {
		
		String sql = generateGetListSql(paramsMap) + " ORDER BY cdate DESC ";
		List<StatCommActivityRegisterModel> list = null;

		try {
			list = getStatDao().list(sql, StatCommActivityRegisterModel.class);
		} catch (AppException e) {
			LogService.error(e);
		}
		
		StringBuilder sb = new StringBuilder("日期,产品,产品分类,渠道,渠道分类,平台,活动类型,活动ID,H5-登记人数,H5-注册人数,APP-注册人数（按设备）,"
				+ "APP-注册人数（按手机号）,api提单数,api成功提单数,借条提单数,访问UV,登录人数,登录人数/访问UV,APP注册人数（按手机号）/访问UV\r\n");
		
		DecimalFormat format = new DecimalFormat("#.##%");
		for(StatCommActivityRegisterModel model: list){

			model.setProductGroupName(this.productGroupMap.get(model.getProductGroupId()));
			model.setChannelGroupName(this.channelGroupMap.get(model.getChannelGroupId()));
			
			String loginToUvRate = "0.00%";
			String appRegisterCountPhoneToUvRate = "0.00%";
			
			if(model.getLoginCount() != null && model.getUv() != null && model.getUv() != 0){
				loginToUvRate = format.format((double)model.getLoginCount() / (double)model.getUv());
			}

			if(model.getAppRegisterCountPhone() != null && model.getUv() != null && model.getUv() != 0){
				appRegisterCountPhoneToUvRate = format.format((double)model.getAppRegisterCountPhone() / (double) model.getUv());
			}

			model.setLoginToUvRate(loginToUvRate);
			model.setAppRegisterCountPhoneToUvRate(appRegisterCountPhoneToUvRate);

			
			sb.append(model.getCreateDate() + ",")
			  .append(model.getProductName() + ",")
			  .append(model.getProductGroupName() + ",")
			  .append(model.getChannelName() + ",")
			  .append(model.getChannelGroupName() + ",")
			  .append(model.getPlatform() + ",")
			  .append(model.getActivityTypeName() + ",")
			  .append(model.getActivityId() + ",")
			  .append(model.getH5CheckInCount() + ",")
			  .append(model.getH5RegisterCount() + ",")
			  .append(model.getAppRegisterCountDevice() + ",")
			  .append(model.getAppRegisterCountPhone() + ",")
			  .append(model.getApiOrderCount() + ",")
			  .append(model.getApiOrderSuccessCount() + ",")
			  .append(model.getLoanReceiptOrderCount() + ",")
			  .append(model.getUv() + ",")
			  .append(model.getLoginCount() + ",")
			  .append(model.getLoginToUvRate() + ",")
			  .append(model.getAppRegisterCountPhoneToUvRate() + "\r\n");
		}
		
		return sb.toString();
		
	}
	
	private String generateGetListSql(Map<String, Object> paramsMap){
		
		String startDate = (String) paramsMap.get("startDate");
		String endDate = (String) paramsMap.get("endDate");
		String prdid = (String) paramsMap.get("prdid");
		String channel = (String) paramsMap.get("channel");
		String platform = (String) paramsMap.get("platform");
		String activity_type = (String) paramsMap.get("activity_type");
		String activity_id = (String) paramsMap.get("activity_id");
		String environment = (String) paramsMap.get("environment");
		String parentProduct = (String) paramsMap.get("parentProduct");
		String channelGroup = (String) paramsMap.get("channelGroup");
		String secondaryChannelGroup = (String) paramsMap.get("secondaryChannelGroup");

		StringBuilder sql = new StringBuilder("SELECT TB_SCAR.cdate AS createDate, TB_CPP.name AS productName,")
				.append(" TB_CPP.parent_id AS productGroupId, TB_CPC.channel_name AS channelName, TB_CPC.channel_group AS channelGroupId, TB_CPC.secondary_channel_group AS secondaryChannelGroupId,")
				.append(" TB_SCAR.platform AS platform, TB_RRA.activity_type_name AS activityTypeName, TB_SCAR.activity_id AS activityId,")
				.append(" TB_SCAR.external_register_count AS h5CheckInCount,TB_SCAR.external_new_register_count AS h5RegisterCount,")
				.append(" TB_SCAR.app_activate_count AS appRegisterCountDevice, TB_SCAR.app_activate_count_phone AS appRegisterCountPhone,")
				.append(" TB_SCAR.api_order_count AS apiOrderCount, TB_SCAR.api_order_success_count AS apiOrderSuccessCount,")
				.append(" TB_SCAR.loan_receipt_order_count AS loanReceiptOrderCount,TB_SCAR.uv AS uv, TB_SCAR.login_count AS loginCount")
				.append(" FROM `stat_comm_activity_register` AS TB_SCAR ")
				.append(" LEFT JOIN loan.comm_product_prdid AS TB_CPP ON TB_SCAR.prd_id = TB_CPP.prdid")
				.append(" LEFT JOIN loan.comm_product_channel AS TB_CPC ON TB_SCAR.channel = TB_CPC.channel_code")
				.append(" LEFT JOIN loan.register_recommend_activity AS TB_RRA ON TB_SCAR.activity_type = TB_RRA.activity_type")
				.append(" WHERE 1 = 1 ");
		
		if(StringUtils.isNotEmpty(startDate)){
			sql.append(" AND TB_SCAR.cdate >='" + startDate + "'");
		}
		
		if(StringUtils.isNotEmpty(endDate)){
			sql.append(" AND TB_SCAR.cdate <='" + endDate + "'");
		}
		
		if(StringUtils.isNotEmpty(prdid)){
			sql.append(" AND TB_SCAR.prd_id='" + prdid + "'");
		}
		
		if(StringUtils.isNotEmpty(channel) && !channel.endsWith("9999")){
			sql.append(" AND TB_SCAR.channel='" + channel + "'");
		}
		
		if(StringUtils.isNotEmpty(platform)){
			sql.append(" AND TB_SCAR.platform='" + platform + "'");
		}
		
		if(StringUtils.isNotEmpty(activity_type)){
			sql.append(" AND TB_SCAR.activity_type='" + activity_type + "'");
		}
		
		if(StringUtils.isNotEmpty(activity_id)){
			sql.append(" AND TB_SCAR.activity_id='" + activity_id + "'");
		}
		
		if(StringUtils.isNotEmpty(environment)){
			sql.append(" AND TB_SCAR.environment='" + environment + "'");
		}
		
		if(StringUtils.isNotBlank(parentProduct)) {
			sql.append(" AND TB_SCAR.`prd_id` IN (SELECT `prdid` FROM `loan`.`comm_product_prdid` WHERE `parent_id` = '" + parentProduct + "')");
		}
		
		if(StringUtils.isNotBlank(channelGroup)) {
			sql.append(" AND TB_SCAR.`channel` IN (SELECT channel_code FROM `loan`.`comm_product_channel` WHERE channel_group = '" + channelGroup +"')");
		}

		if(StringUtils.isNotBlank(secondaryChannelGroup)) {
			sql.append(" AND TB_CPC.`secondary_channel_group` = '" + secondaryChannelGroup + "'");
		}
		
		return sql.toString();
	}
	

}
